//import angualr core
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';

//import third package
import 'rxjs/add/operator/switchMap';

//import service
import { HeroService } from '../../service/hero.service';

//import class
import { Hero } from '../../domain/hero';

@Component({
  selector: 'app-my-hero-list',
  templateUrl: './my-hero-list.component.html',
  styleUrls: ['./my-hero-list.component.css'],
  providers: [HeroService]
})
export class MyHeroListComponent implements OnInit {

  myId: number;
  heroes: Hero[];
  selectedHero: Hero;

  constructor(
    private heroService: HeroService,
    private route: ActivatedRoute,
    private router: Router
  ) { }

  ngOnInit() {
    this.myId = <number><any>localStorage.getItem('userId');
    this.heroService.getHeroesByOwnerId(this.myId)
      .then(heroes => this.heroes = heroes);
  }

  addHero(name: string): void {
    name = name.trim();
    if (!name) { return; }
    this.heroService.createHeroByNameUserId(name,this.myId)
      .then(hero => {
        this.heroes.push(hero);
        this.selectedHero = null;
      });
  }

  deleteHero(hero: Hero): void {
    this.heroService   
    this.heroes = this.heroes.filter(h => h !== hero);
    if (this.selectedHero === hero) { this.selectedHero = null; }
    hero.ownerId = 0;
    this.heroService.updateHero(hero);
  }

  onSelect(hero: Hero): void {
    this.selectedHero = hero;
    this.router.navigate(['/myhero', this.selectedHero.id]);
  }
}
